package com.lib.framework.widget

import android.app.Activity
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.text.Selection
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.util.TypedValue
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import com.lib.framework.manager.ContextManager
import com.lib.framework.widget.dialog.LoadingDialog
import java.lang.Exception


/**
 * 控件工具接口类
 *
 * @author keanbin
 */
class WidgetUtil {

    companion object {

        /**
         * 设置EditText的光标在文本末尾
         *
         * @param editText
         */
        fun setEditTextCursorEnd(editText: EditText?) {
            if (editText == null) {
                return
            }

            val text = editText.text
            if (text is Spannable) {
                val spanText = text as Spannable
                Selection.setSelection(spanText, text.length)
            }
        }

        /**
         * 显示提示对话框
         */
        fun showPromptDialog(context: Context, text: String) {
            ToastUtil.showToastViewDefault(context, text)
        }

        /**
         * 显示提示Toast
         */
        @JvmStatic
        fun showToast(text: String) {
            ToastUtil.showToast(ContextManager.applicationContext, text)
        }

        /**
         * 显示提示Toast：错误样式
         */
        @JvmStatic
        fun showPromptToastError(context: Context, text: String) {
            ToastUtil.showToastViewError(context, text)
        }

        /**
         * 显示提示Toast：正确样式
         */
        @JvmStatic
        fun showPromptToastOK(context: Context, text: String) {
            ToastUtil.showToastViewOK(context, text)
        }

        /**
         * 创建 Loading 对话框
         */
        fun createLoadingDialog(context: Context, text: String? = null): LoadingDialog {
            val dialog = LoadingDialog(context)
            dialog.setText(text)
            dialog.setShowDelayTime(300)
            return dialog
        }

        /**
         * 打开软键盘
         *
         * @param view
         * @param context
         */
        fun openKeybord(view: View, context: Context) {
            val imm = context
                    .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(view, 0)
        }

        /**
         * 关闭软键盘
         *
         * @param view
         * @param context
         */
        fun closeKeybord(view: View, context: Context) {
            val imm = context
                    .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }

        /**
         * 判断当前软键盘是否打开
         *
         * @param activity
         * @return
         */
        fun isSoftInputShow(activity: Activity): Boolean {
            // 虚拟键盘隐藏 判断view是否为空
            val view = activity.window.peekDecorView()
            if (view != null) {
                // 隐藏虚拟键盘
                val inputmanger = activity
                        .getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
                //       inputmanger.hideSoftInputFromWindow(view.getWindowToken(),0);

                return !(!inputmanger.isActive || activity.window.currentFocus == null)
            }
            return false
        }

        /**
         * px to dp
         */
        @JvmStatic
        fun pxTodp(context: Context, pxValue: Float): Int {
            val fontScale = context.resources.displayMetrics.scaledDensity
            return (pxValue / fontScale + 0.5f).toInt()
        }

        /**
         * dp to px
         */
        @JvmStatic
        fun dpTopx(context: Context, dp: Int): Int {
            val displayMetrics = context.resources.displayMetrics
            return (dp * displayMetrics.density + 0.5).toInt()
        }

        @JvmStatic
        fun spToPx(context: Context, sp: Int): Int {
            val displayMetrics = context.resources.displayMetrics
            return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp.toFloat(), displayMetrics).toInt()
        }

        /**
         * 从资源文件（如：color.xml）获取颜色
         */
        @JvmStatic
        fun getColorFromRes(resId: Int): Int {
            return ContextManager.applicationContext.resources.getColor(resId)
        }

        /**
         * 从资源文件 获取图片
         */
        fun getDrawableFromRes(id: Int): Drawable {
            return ContextManager.applicationContext.resources.getDrawable(id)
        }

        /**
         * 从资源文件 获取字符串数组
         */
        fun getStringArrayFromRes(id: Int): Array<String> {
            return ContextManager.applicationContext.resources.getStringArray(id)
        }

        /**
         * 从资源文件 获取字符串
         */
        fun getStringFromRes(id: Int): String {
            return ContextManager.applicationContext.getString(id)
        }

        /**
         * 设置控制 Visibility 属性
         */
        fun setVisibility(view: View, visibility: Int) {
            if (view.visibility == visibility) return

            view.visibility = visibility
        }

        /**
         * 设置点击文本样式
         *
         * @param spannableStringBuilder 已包含 text 的文本的样式 SpannableStringBuilder
         * @param clickText 加点击样式的文本
         * @param startIndex 总文本开始查找的位置
         */
        fun setClickText(spannableStringBuilder: SpannableStringBuilder, clickText: String,
                                 startIndex: Int, textColor: Int, onClick: () -> Unit) {
            val clickableSpan = object : ClickableSpan() {
                override fun onClick(widget: View) {
                    onClick()
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = textColor//Color.parseColor("#FFC800")
                    ds.isUnderlineText = false
                }
            }
            setTextSpan(spannableStringBuilder, mutableListOf(clickableSpan), clickText, startIndex)
        }

        /**
         * 设置文本特殊样式
         *
         * @param spannableStringBuilder 已包含 text 的文本的样式 SpannableStringBuilder
         * @param spans 样式列表
         * @param text 加样式的文本
         * @param startIndex 总文本开始查找的位置
         */
        fun setTextSpan(spannableStringBuilder: SpannableStringBuilder, spans: List<Any>, text: String,
                                startIndex: Int = 0) {
            if (spans.isEmpty()) return

            val allText = spannableStringBuilder.toString()
            if (allText.isEmpty()) return
            if (text.isEmpty()) return

            val start = allText.indexOf(text, startIndex)
            if (start < 0 || start >= allText.length) return

            var end = start + text.length
            if (end >= allText.length) {
                end = allText.length
            }

            for (span in spans) {
                spannableStringBuilder.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            }
        }

        /**
         * 代码设置光标颜色
         *
         * @param editText 你使用的EditText
         * @param color    光标颜色
         */
        fun setCursorDrawableColor(editText: EditText, color: Int) {
            try {
                val fCursorDrawableRes = TextView::class.java.getDeclaredField("mCursorDrawableRes") //获取这个字段
                fCursorDrawableRes.setAccessible(true) //代表这个字段、方法等等可以被访问
                val mCursorDrawableRes: Int = fCursorDrawableRes.getInt(editText)
                val fEditor = TextView::class.java.getDeclaredField("mEditor")
                fEditor.setAccessible(true)
                val editor: Any = fEditor.get(editText)
                val clazz: Class<*> = editor.javaClass
                val fCursorDrawable = clazz.getDeclaredField("mCursorDrawable")
                fCursorDrawable.setAccessible(true)
                val drawables =
                    arrayOfNulls<Drawable>(2)
                drawables[0] = editText.context.resources.getDrawable(mCursorDrawableRes)
                drawables[1] = editText.context.resources.getDrawable(mCursorDrawableRes)
                drawables[0]?.setColorFilter(color, PorterDuff.Mode.SRC_IN) //SRC_IN 上下层都显示。下层居上显示。
                drawables[1]?.setColorFilter(color, PorterDuff.Mode.SRC_IN)
                fCursorDrawable.set(editor, drawables)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}